/*客户端主程序
接收网络消息 */
#include <memory>
#include <functional>

#include "UdpServer.hpp"
#include "Thread.hpp"
#include"LockGuard.hpp"

using namespace ThreadMoudle;

int client_init(std::string clientIP, uint16_t clientPort)
{
    int clientfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (clientfd < 0)
    {
        LOG(FATAL, "client socket error\n");
        exit(1);
    }

    return clientfd;
}
void SendMessage(int clientfd, uint16_t clientPort, std::string clientIP, const std::string &name)
{
    //LOG(DEBUG, "SendMessage\n");
    struct sockaddr_in sever;
    memset(&sever, 0, sizeof(sever));
    sever.sin_family = AF_INET;
    sever.sin_port = htons(clientPort);
    sever.sin_addr.s_addr = inet_addr(clientIP.c_str());
    while (true)
    {
        std::string line;
        //LOG(INFO, "Please Enter#");
        std::getline(std::cin, line);
        int n = sendto(clientfd, line.c_str(), line.size(), 0, (struct sockaddr *)&sever, sizeof(sever));
    }
}
void RecvMessage(int clientfd, const std::string &name)
{
    //LOG(DEBUG, "RecvMessage\n");

    while (true)
    {
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char inbuffer[1024];
        int m = recvfrom(clientfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&temp, &len);
        if (m > 0)
        {
            inbuffer[m] = 0;
            std::cerr << inbuffer << std::endl;
        }
        else
        {
            std::cerr << "recv error" << std::endl;
            break;
        }
    }
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        LOG(FATAL, "too few arguments in cmd\n");
        exit(1);
    }
    std::string clientIP = argv[1];
    uint16_t clientPort = std::stoi(argv[2]);

    int sockfd = client_init(clientIP, clientPort);

    pthread_mutex_t gmutex;
    Thread recver("recver-thread", std::bind(RecvMessage, sockfd, std::placeholders::_1));
    Thread sender("sender-thread", std::bind(SendMessage, sockfd, clientPort, clientIP, std::placeholders::_1));

    recver.Start();
    sender.Start();

    recver.join();
    sender.join();
}